package com.nanfang51g3.ckz.ui.home;

import android.os.Environment;

import com.nanfang51g3.ckz.di.ApiModule;
import com.nanfang51g3.ckz.domain.DownloadBean;
import com.nanfang51g3.ckz.domain.HttpResultBean;
import com.nanfang51g3.ckz.exec.Api2Exception;
import com.nanfang51g3.ckz.http.HttpResultFunc;
import com.nanfang51g3.ckz.http.RestApi;
import com.nanfang51g3.ckz.http.SubscriberInterface;
import com.nanfang51g3.ckz.http.downloadprogress.DownLoadApi;
import com.nanfang51g3.ckz.http.downloadprogress.ProgressListener;
import com.nanfang51g3.ckz.http.downloadprogress.ProgressResponseBody;
import com.nanfang51g3.ckz.ui.base.BasePresenter;
import com.nanfang51g3.ckz.ui.index.IndexPresenterModule;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.widget.progress.NumberProgressBar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;

import javax.inject.Inject;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/4/13.
 */
public class HomeMainPresenter extends BasePresenter implements HomeMainContract.HomeMainActionsListener {

    private String message;
    private final RestApi _restApi;
    private final HomeMainContract.View mView;
    private boolean pullDown = false;

    /**
     * @see ApiModule#provideRetrofit()
     */
    @Inject
    Retrofit retrofit;

    @Inject
    public HomeMainPresenter(RestApi restApi, HomeMainContract.View mView) {
        KLog.i("TAG", "进入了...IndexPresenter");
        /**
         * @see ApiModule#provideRestApi(Retrofit)
         */
        this._restApi = restApi;
        KLog.i("TAG", _restApi == null ? "进入了...is null" : "进入了...not null");
        /**
         * @see IndexPresenterModule#provideIndexContractView()
         */
        this.mView = mView;
        KLog.i("TAG", mView == null ? "进入了...is null" : "进入了...not null");
    }

    class DownloadApkHttpResultFunc<T> extends HttpResultFunc<T> {
        @Override
        public T call(HttpResultBean<T> httpResult) {
            KLog.i("Evd", httpResult.getCode() + "-" + httpResult.getInfo() + "-" + httpResult.getData().toString());
            if (httpResult.getCode() == 0) {
                throw new Api2Exception(httpResult.getInfo());
            }
            return httpResult.getData();
        }
    }

    @Override
    public void isDownloadApk(String versionCode, String versionName, final boolean isShowMessage) {

        Observable observable = _restApi.isDownloadApk(versionCode, versionName);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new DownloadApkHttpResultFunc<DownloadBean>())
                .subscribe(new SubscriberInterface<DownloadBean>() {
                    @Override
                    public void _onError(String msg) {
                        KLog.i("Evd", "_onError " + msg);
                        if (isShowMessage) {
                            mView.noUpdatesVersionCode(msg);
                        }

                    }

                    @Override
                    public void onCompleted() {
                        KLog.i("Evd", "onCompleted ");

                    }

                    @Override
                    public void onNext(DownloadBean o) {
                        KLog.i("Evd", "onNext " + o.toString());
//                        mView.downloadApk(o.getVersionname());
                        /**
                         * @see HomeMainActivity#showDialog(String, String)
                         * @see com.nanfang51g3.ckz.ui.fragment.home.HomeMeFragment#showDialog(String, String)
                         */
                        mView.showDialog(o.getVersionname(), o.getApkurl());

                    }
                });
    }

    @Override
    public void downloadApk(final String versionName, String apkUrl, final NumberProgressBar progressBar) {
        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl("http://ckt.51g3.com/");
        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        okhttp3.Response orginalResponse = chain.proceed(chain.request());

                        return orginalResponse.newBuilder()
                                .body(new ProgressResponseBody(orginalResponse.body(), new ProgressListener() {
                                    @Override
                                    public void onProgress(final long progress, long total, boolean done) {
//                                        KLog.e("Evd", Looper.myLooper() + "");
//                                        KLog.e("Evd", "onProgress: " + "total ---->" + total + "done ---->" + progress + "---" + (int) progress % 100);
                                        mView.updateProgress(progress);
                                    }
                                }))
                                .build();
                    }
                })
                .build();
        DownLoadApi api = builder.client(client)
                .build().create(DownLoadApi.class);

        final String[] values = apkUrl.split("=");
        KLog.i("Evd", values[1]);
        Call<ResponseBody> call = api.downloadApk(Collections.singletonMap("type", values[1]));
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                KLog.i("Evd", "onResponse");
                ResponseBody body = response.body();
                File futureStudioIconFile = new File(Environment.getExternalStorageDirectory()
                        .getAbsolutePath() + "/" + versionName + ".apk");
                try {
                    // todo change the file location/name according to your needs
                    InputStream inputStream = null;
                    OutputStream outputStream = null;
                    try {
                        byte[] fileReader = new byte[4096];
                        long fileSize = body.contentLength();//获取长度
                        long fileSizeDownloaded = 0;
                        inputStream = body.byteStream();//获取读取流
                        outputStream = new FileOutputStream(futureStudioIconFile);

                        while (true) {
                            int read = inputStream.read(fileReader);
                            if (read == -1) {
                                break;
                            }
                            outputStream.write(fileReader, 0, read);
                            fileSizeDownloaded += read;
//                            KLog.i("Evd", "file download: " + fileSizeDownloaded + " of " + fileSize);
//

                        }
                        outputStream.flush();
                        /**
                         * @see HomeMainActivity#installationApk(File)
                         * @see com.nanfang51g3.ckz.ui.fragment.home.HomeMeFragment#installationApk(File)
                         */
                        mView.installationApk(futureStudioIconFile);
                    } catch (IOException e) {
                        KLog.i("Evd", "IOException 1 - " + e.toString());
                    } finally {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    }
                } catch (IOException e) {
                    KLog.i("Evd", "IOException 2 - " + e.toString());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                KLog.i("Evd", "onFailure");
            }
        });

    }
}
